#!/bin/bash
# filepath: /Users/aibokalv/Mycode/coding_pc_nuxtcoding_pc_nuxt/scripts/oss-async.sh

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 检查是否跳过 OSS 上传
if [[ "$SKIP_OSS" == "1" ]]; then
    echo -e "${YELLOW}🤖 检测到跳过模式 (SKIP_OSS=1)${NC}"
    echo -e "${BLUE}⏭️  跳过 OSS 上传步骤${NC}"
    echo -e "${GREEN}✅ OSS 同步已跳过${NC}"
    exit 0
fi

# 配置变量
OSS_BUCKET="oss://xiaobao2"
OSS_PATH="/ai/pc/build/_nuxt/"
OSS_BUILDS_PATH="/ai/pc/build/_nuxt/builds/"

# 支持多个构建路径
NUXT3_DIST_PATH=".output/public/_nuxt"
LEGACY_DIST_PATH=".nuxt/dist/client"
MANIFEST_PATH=".output/public/_nuxt/builds"

FULL_OSS_PATH="${OSS_BUCKET}${OSS_PATH}"
FULL_OSS_BUILDS_PATH="${OSS_BUCKET}${OSS_BUILDS_PATH}"

echo -e "${BLUE}🚀 开始 OSS 同步任务...${NC}"

# 检查执行模式
if [[ "$AUTO_CONFIRM" == "1" ]]; then
    echo -e "${YELLOW}🤖 自动确认模式 (AUTO_CONFIRM=1)${NC}"
    CONFIRM_MODE="auto"
else
    echo -e "${YELLOW}👤 手动确认模式${NC}"
    CONFIRM_MODE="manual"
fi

echo -e "${YELLOW}📋 项目: Nuxt 3 应用${NC}"
echo -e "${YELLOW}🎯 目标: 阿里云 OSS${NC}"

# 检查构建文件
echo ""
echo -e "${YELLOW}📁 检查构建文件...${NC}"

# 检查可用的构建路径
AVAILABLE_PATHS=()
TOTAL_FILES=0
TOTAL_SIZE="0"

# 检查 Nuxt 3 构建路径
if [ -d "$NUXT3_DIST_PATH" ]; then
    nuxt3_files=$(find "$NUXT3_DIST_PATH" -type f 2>/dev/null | wc -l | tr -d ' ')
    if [ "$nuxt3_files" -gt 0 ]; then
        AVAILABLE_PATHS+=("$NUXT3_DIST_PATH")
        nuxt3_size=$(du -sh "$NUXT3_DIST_PATH" 2>/dev/null | cut -f1)
        echo -e "${GREEN}✅ 发现 Nuxt 3 构建: $NUXT3_DIST_PATH ($nuxt3_files 个文件, $nuxt3_size)${NC}"
        TOTAL_FILES=$((TOTAL_FILES + nuxt3_files))
    fi
fi

# 检查 Legacy 构建路径
if [ -d "$LEGACY_DIST_PATH" ]; then
    legacy_files=$(find "$LEGACY_DIST_PATH" -type f 2>/dev/null | wc -l | tr -d ' ')
    if [ "$legacy_files" -gt 0 ]; then
        AVAILABLE_PATHS+=("$LEGACY_DIST_PATH")
        legacy_size=$(du -sh "$LEGACY_DIST_PATH" 2>/dev/null | cut -f1)
        echo -e "${GREEN}✅ 发现 Legacy 构建: $LEGACY_DIST_PATH ($legacy_files 个文件, $legacy_size)${NC}"
        TOTAL_FILES=$((TOTAL_FILES + legacy_files))
    fi
fi

# 检查是否找到任何构建文件
if [ ${#AVAILABLE_PATHS[@]} -eq 0 ]; then
    echo -e "${RED}❌ 错误: 未找到任何构建文件${NC}"
    echo -e "${YELLOW}💡 检查的路径:${NC}"
    echo -e "   - Nuxt 3: $NUXT3_DIST_PATH"
    echo -e "   - Legacy: $LEGACY_DIST_PATH"
    echo -e "${YELLOW}💡 请先运行构建命令: pnpm run build:cdn${NC}"
    
    # 显示目录结构以便调试
    if [ -d ".output" ]; then
        echo -e "${YELLOW}🔍 当前 .output 目录结构:${NC}"
        find .output -type d -maxdepth 3 2>/dev/null | head -10 | sed 's/^/     /'
    fi
    
    if [ -d "_nuxt" ]; then
        echo -e "${YELLOW}🔍 当前 _nuxt 目录结构:${NC}"
        find _nuxt -type d -maxdepth 3 2>/dev/null | head -10 | sed 's/^/     /'
    fi
    
    exit 1
fi

echo -e "${GREEN}✅ 构建文件检查通过 (找到 ${#AVAILABLE_PATHS[@]} 个构建目录)${NC}"

# 检查 ossutil
echo ""
echo -e "${YELLOW}🔧 检查 ossutil...${NC}"
if ! command -v ossutil &> /dev/null; then
    echo -e "${RED}❌ 错误: ossutil 未安装${NC}"
    echo -e "${YELLOW}💡 安装方法: https://help.aliyun.com/document_detail/120075.html${NC}"
    exit 1
fi

echo -e "${GREEN}✅ ossutil 版本: $(ossutil version 2>/dev/null | head -1)${NC}"



# 统计所有构建路径的文件信息
echo ""
echo -e "${YELLOW}📊 文件统计:${NC}"

total_js=0
total_css=0
total_images=0
total_fonts=0
total_other=0

echo -e "   ${BLUE}构建路径详情:${NC}"

for path in "${AVAILABLE_PATHS[@]}"; do
    path_files=$(find "$path" -type f 2>/dev/null | wc -l | tr -d ' ')
    path_size=$(du -sh "$path" 2>/dev/null | cut -f1)
    
    js_count=$(find "$path" -name "*.js" 2>/dev/null | wc -l | tr -d ' ')
    css_count=$(find "$path" -name "*.css" 2>/dev/null | wc -l | tr -d ' ')
    image_count=$(find "$path" \( -name "*.png" -o -name "*.jpg" -o -name "*.jpeg" -o -name "*.gif" -o -name "*.svg" -o -name "*.webp" \) 2>/dev/null | wc -l | tr -d ' ')
    font_count=$(find "$path" \( -name "*.woff" -o -name "*.woff2" -o -name "*.ttf" -o -name "*.eot" \) 2>/dev/null | wc -l | tr -d ' ')
    other_count=$((path_files - js_count - css_count - image_count - font_count))
    
    echo -e "     📁 $path"
    echo -e "       总文件: ${GREEN}$path_files${NC} 个 (${GREEN}$path_size${NC})"
    echo -e "       JS: ${GREEN}$js_count${NC}, CSS: ${GREEN}$css_count${NC}, 图片: ${GREEN}$image_count${NC}, 字体: ${GREEN}$font_count${NC}, 其他: ${GREEN}$other_count${NC}"
    
    total_js=$((total_js + js_count))
    total_css=$((total_css + css_count))
    total_images=$((total_images + image_count))
    total_fonts=$((total_fonts + font_count))
    total_other=$((total_other + other_count))
done

echo ""
echo -e "   ${BLUE}总计统计:${NC}"
echo -e "   构建路径数: ${GREEN}${#AVAILABLE_PATHS[@]}${NC} 个"
echo -e "   总文件数: ${GREEN}$TOTAL_FILES${NC} 个"
echo -e "   - JS 文件: ${GREEN}$total_js${NC} 个"
echo -e "   - CSS 文件: ${GREEN}$total_css${NC} 个"
echo -e "   - 图片文件: ${GREEN}$total_images${NC} 个"
echo -e "   - 字体文件: ${GREEN}$total_fonts${NC} 个"
echo -e "   - 其他文件: ${GREEN}$total_other${NC} 个"

# 检查 manifest 文件
manifest_files=0
manifest_size="0B"
if [ -d "$MANIFEST_PATH" ]; then
    manifest_files=$(find "$MANIFEST_PATH" -type f 2>/dev/null | wc -l | tr -d ' ')
    if [ "$manifest_files" -gt 0 ]; then
        manifest_size=$(du -sh "$MANIFEST_PATH" 2>/dev/null | cut -f1)
    fi
fi

echo -e "   Manifest 文件: ${GREEN}$manifest_files${NC} 个 (${GREEN}$manifest_size${NC})"

# 文件预览
echo ""
echo -e "${YELLOW}📋 部分文件预览:${NC}"
echo -e "   ${BLUE}JS 文件:${NC}"
for path in "${AVAILABLE_PATHS[@]}"; do
    find "$path" -name "*.js" 2>/dev/null | head -2 | sed "s|^|     $path/|"
done | head -5

echo -e "   ${BLUE}CSS 文件:${NC}"
for path in "${AVAILABLE_PATHS[@]}"; do
    find "$path" -name "*.css" 2>/dev/null | head -2 | sed "s|^|     $path/|"
done | head -5

if [ "$manifest_files" -gt 0 ]; then
    echo -e "   ${BLUE}Manifest 文件:${NC}"
    find "$MANIFEST_PATH" -type f 2>/dev/null | head -3 | sed 's/^/     /'
fi

echo ""
echo -e "${YELLOW}☁️  目标路径:${NC}"
echo -e "   客户端文件: ${BLUE}$FULL_OSS_PATH${NC}"
if [ "$manifest_files" -gt 0 ]; then
    echo -e "   Manifest 文件: ${BLUE}$FULL_OSS_BUILDS_PATH${NC}"
fi

echo ""
echo -e "${YELLOW}📌 路径映射示例:${NC}"
if [ "$total_js" -gt 0 ]; then
    sample_js=$(find "${AVAILABLE_PATHS[0]}" -name "*.js" 2>/dev/null | head -1)
    if [ -n "$sample_js" ]; then
        js_filename=$(basename "$sample_js")
        echo -e "   ${sample_js} -> ${BLUE}https://cdn.codinghou.cn/ai/pc/build/_nuxt/${js_filename}${NC}"
    fi
fi

if [ "$total_css" -gt 0 ]; then
    sample_css=$(find "${AVAILABLE_PATHS[0]}" -name "*.css" 2>/dev/null | head -1)
    if [ -n "$sample_css" ]; then
        css_filename=$(basename "$sample_css")
        echo -e "   ${sample_css} -> ${BLUE}https://cdn.codinghou.cn/ai/pc/build/_nuxt/${css_filename}${NC}"
    fi
fi

# 确认操作
echo ""
echo -e "${RED}⚠️  警告: 即将删除 OSS 路径下的所有文件并上传新文件${NC}"
echo -e "${YELLOW}📍 影响的 OSS 路径:${NC}"
echo -e "   - $FULL_OSS_PATH"
if [ "$manifest_files" -gt 0 ]; then
    echo -e "   - $FULL_OSS_BUILDS_PATH"
fi

echo -e "${YELLOW}📍 将上传的本地路径:${NC}"
for path in "${AVAILABLE_PATHS[@]}"; do
    echo -e "   - $path"
done

# 根据模式处理确认
if [[ "$CONFIRM_MODE" == "auto" ]]; then
    echo -e "${YELLOW}🤖 自动确认模式，直接执行...${NC}"
    REPLY="y"
else
    read -p "是否继续? (y/N): " -n 1 -r
    echo ""
fi

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}❌ 操作已取消${NC}"
    exit 0
fi

echo ""
echo -e "${YELLOW}🗑️  正在清理 OSS 路径...${NC}"

# 删除客户端文件路径
echo -e "   删除客户端文件: $FULL_OSS_PATH"
if ossutil rm "$FULL_OSS_PATH" -r -f >/dev/null 2>&1; then
    echo -e "   ${GREEN}✅ OSS 客户端文件删除成功${NC}"
else
    echo -e "   ${YELLOW}⚠️  OSS 客户端路径可能为空或删除失败，继续上传...${NC}"
fi

# 删除 builds 路径（如果有 manifest 文件）
if [ "$manifest_files" -gt 0 ]; then
    echo -e "   删除 Manifest 文件: $FULL_OSS_BUILDS_PATH"
    if ossutil rm "$FULL_OSS_BUILDS_PATH" -r -f >/dev/null 2>&1; then
        echo -e "   ${GREEN}✅ OSS builds 文件删除成功${NC}"
    else
        echo -e "   ${YELLOW}⚠️  OSS builds 路径可能为空或删除失败，继续上传...${NC}"
    fi
fi

echo ""
echo -e "${YELLOW}⬆️  开始上传文件...${NC}"

# 上传所有构建路径的文件
upload_start_time=$(date +%s)
upload_success=true

for i in "${!AVAILABLE_PATHS[@]}"; do
    path="${AVAILABLE_PATHS[$i]}"
    path_num=$((i + 1))
    
    echo -e "   📦 [$path_num/${#AVAILABLE_PATHS[@]}] 上传构建文件: $path"
    echo -e "   ${BLUE}执行命令:${NC} ossutil cp \"$path/\" \"$FULL_OSS_PATH\" -r -f --parallel 5 --part-size 10"
    
    if ossutil cp "$path/" "$FULL_OSS_PATH" -r -f  2>/dev/null; then
        echo -e "   ${GREEN}✅ [$path_num/${#AVAILABLE_PATHS[@]}] $path 上传成功${NC}"
    else
        echo -e "   ${RED}❌ [$path_num/${#AVAILABLE_PATHS[@]}] $path 上传失败${NC}"
        echo -e "   ${YELLOW}💡 检查文件权限和路径...${NC}"
        ls -la "$path" 2>/dev/null | head -5
        upload_success=false
    fi
done

if [ "$upload_success" = false ]; then
    echo -e "${RED}❌ 部分文件上传失败${NC}"
    echo -e "${YELLOW}💡 检查网络连接和 OSS 配置...${NC}"
    exit 1
fi

upload_end_time=$(date +%s)
upload_duration=$((upload_end_time - upload_start_time))
echo -e "   ${GREEN}✅ 所有客户端文件上传完成${NC} (总耗时: ${upload_duration}s)"

# 上传 manifest 文件（如果存在）
if [ "$manifest_files" -gt 0 ]; then
    echo -e "   📦 上传 Manifest 文件到 $FULL_OSS_BUILDS_PATH"
    echo -e "   ${BLUE}执行命令:${NC} ossutil cp \"$MANIFEST_PATH/\" \"$FULL_OSS_BUILDS_PATH\" -r -f "

    if ossutil cp "$MANIFEST_PATH/" "$FULL_OSS_BUILDS_PATH" -r -f  2>/dev/null; then
        echo -e "   ${GREEN}✅ Manifest 文件上传成功${NC}"
    else
        echo -e "   ${RED}❌ Manifest 文件上传失败${NC}"
        echo -e "   ${YELLOW}💡 检查文件权限和路径...${NC}"
        ls -la "$MANIFEST_PATH" 2>/dev/null | head -5
        exit 1
    fi
fi

echo ""
echo -e "${YELLOW}🔍 验证上传结果...${NC}"

# 验证上传结果
echo -e "   正在统计 OSS 文件..."

uploaded_files=$(ossutil ls "$FULL_OSS_PATH" -r 2>/dev/null | grep -v "/$" | wc -l | tr -d ' ')
uploaded_js=$(ossutil ls "$FULL_OSS_PATH" -r 2>/dev/null | grep "\.js$" | wc -l | tr -d ' ')
uploaded_css=$(ossutil ls "$FULL_OSS_PATH" -r 2>/dev/null | grep "\.css$" | wc -l | tr -d ' ')

# 验证 manifest 文件上传结果
uploaded_manifest=0
if [ "$manifest_files" -gt 0 ]; then
    uploaded_manifest=$(ossutil ls "$FULL_OSS_BUILDS_PATH" -r 2>/dev/null | grep -v "/$" | wc -l | tr -d ' ')
fi

echo -e "   ${GREEN}📊 上传结果统计:${NC}"
echo -e "     OSS 总文件数: ${GREEN}$uploaded_files${NC} 个"
echo -e "     JS 文件: ${GREEN}$uploaded_js${NC} 个"
echo -e "     CSS 文件: ${GREEN}$uploaded_css${NC} 个"
if [ "$manifest_files" -gt 0 ]; then
    echo -e "     Manifest 文件: ${GREEN}$uploaded_manifest${NC} 个"
fi

# 对比本地和远程文件数量
echo ""
echo -e "   ${YELLOW}📋 文件对比:${NC}"
echo -e "     本地 -> OSS"
echo -e "     JS: $total_js -> $uploaded_js"
echo -e "     CSS: $total_css -> $uploaded_css"
if [ "$manifest_files" -gt 0 ]; then
    echo -e "     Manifest: $manifest_files -> $uploaded_manifest"
fi

# 验证上传是否成功
success=true
if [ "$uploaded_files" -eq 0 ]; then
    echo -e "   ${RED}❌ 客户端文件上传验证失败${NC}"
    success=false
fi

if [ "$manifest_files" -gt 0 ] && [ "$uploaded_manifest" -eq 0 ]; then
    echo -e "   ${RED}❌ Manifest 文件上传验证失败${NC}"
    success=false
fi

if [ "$success" = true ]; then
    echo ""
    echo -e "${GREEN}🎉 OSS 同步验证成功!${NC}"
    
    echo ""
    echo -e "${YELLOW}📋 上传文件示例 URL:${NC}"
    
    # 显示 JS 文件示例
    if [ "$uploaded_js" -gt 0 ]; then
        echo -e "   ${BLUE}JS 文件:${NC}"
        ossutil ls "$FULL_OSS_PATH" -r 2>/dev/null | grep "\.js$" | head -3 | while read line; do
            if [[ "$line" =~ \.js$ ]]; then
                relative_path=${line#$OSS_BUCKET}
                echo -e "     ${GREEN}https://cdn.codinghou.cn${relative_path}${NC}"
            fi
        done
    fi
    
    # 显示 CSS 文件示例
    if [ "$uploaded_css" -gt 0 ]; then
        echo -e "   ${BLUE}CSS 文件:${NC}"
        ossutil ls "$FULL_OSS_PATH" -r 2>/dev/null | grep "\.css$" | head -3 | while read line; do
            if [[ "$line" =~ \.css$ ]]; then
                relative_path=${line#$OSS_BUCKET}
                echo -e "     ${GREEN}https://cdn.codinghou.cn${relative_path}${NC}"
            fi
        done
    fi
    
    echo ""
    echo -e "${YELLOW}🔗 CDN 配置信息:${NC}"
    echo -e "   CDN 基础路径: ${BLUE}https://cdn.codinghou.cn/ai/pc/build${NC}"
    echo -e "   配置来源: nuxt.config.ts -> app.cdnURL"
    
else
    echo ""
    echo -e "${RED}❌ 验证失败: OSS 中没有找到预期的文件${NC}"
    echo -e "${YELLOW}💡 诊断信息:${NC}"
    echo -e "   ${YELLOW}客户端文件路径:${NC}"
    ossutil ls "$FULL_OSS_PATH" -r 2>/dev/null | head -5 || echo "     路径为空或无法访问"
    
    exit 1
fi

echo ""
echo -e "${GREEN}✨ OSS 同步任务完成!${NC}"
echo -e "${YELLOW}📊 任务总结:${NC}"
echo -e "   ✅ 执行模式: ${GREEN}$CONFIRM_MODE${NC}"
echo -e "   ✅ 构建路径: ${GREEN}${#AVAILABLE_PATHS[@]}${NC} 个"
echo -e "   ✅ 本地文件: ${GREEN}$TOTAL_FILES${NC} 个"
echo -e "   ✅ OSS 文件: ${GREEN}$uploaded_files${NC} 个"
echo -e "   ✅ OSS Bucket: ${GREEN}$OSS_BUCKET${NC}"
echo -e "   ✅ CDN 域名: ${GREEN}https://cdn.codinghou.cn${NC}"

echo ""
echo -e "${BLUE}🚀 静态资源已同步到 CDN!${NC}"